// Copyright (c) 2002 Cunningham & Cunningham, Inc.
// Released under the terms of the GNU General Public License version 2 or later.

package fat
{

import com.fit4as.fit.*;

public class Color extends PrimitiveFixture {

    public var actualRow : Parse;

    override public function doRows(rows : Parse) : void {
        actualRow = Table.table.parts;
        if (rows.size() != actualRow.size())
            throw new Exception("wrong size table");
        super.doRows(rows);
    }

    override public function doRow(row : Parse) : void {
        super.doRow(row);
        actualRow = actualRow.more;
    }

    override public function doCell(cell : Parse, columnNumber : int) : void {
        trace("\n\ndoCell " + [ columnNumber, cell.text(), cell.tag, cell.body, actualRow.parts.text(), cell ]);
        check(cell, color(actualRow.parts.at(columnNumber)));
    }

    override public function check(... rest) : void
    {
        trace("check " + [ rest[0].text(), rest[1]]);
        super.check.apply(this, rest);
    }

    private function color(cell : Parse) : String {
        var b : String = extract(cell.tag, "bgcolor=\"", "white");
        var f : String = extract(cell.body, "<font color=", "black");
        trace("color " + [b,f]);
        return f == "black" ? b : f + "/" + b;
    }

    private function extract(text : String, pattern : String, defaultColor : String) : String {
        var index : int = text.indexOf(pattern);
        if (index < 0) return defaultColor;
        index += pattern.length;
        return decode(text.substring(index, index + 7));
    }

    private function decode(code : String) : String {
        trace("decode " + code);
        return code == Fixture.red ? "red" :
               code == Fixture.green ? "green" :
               code == Fixture.yellow ? "yellow" :
               code == Fixture.gray ? "gray" :
               code == "#808080" ? "gray" :
               code;
    }

}
}